#!/usr/bin/python3
# -*- coding: utf-8 -*-

from fastapi import FastAPI, Response, status
from fastapi.responses import JSONResponse, HTMLResponse, PlainTextResponse, StreamingResponse, FileResponse, RedirectResponse
from app import app

@app.get("/plain_text_demo")
async def plain_text_demo():
    # 默认响应头的 content-type 是 application/json
    return "hello fastapi"


@app.get("/plain_text_demo2")
async def plain_text_demo():
    return Response(content="hello fastapi 2", media_type="text/plain")


@app.get("/html_demo")
async def html_demo():
    html_text = "<h1> hello fastapi </>"
    return Response(content=html_text, media_type="text/html")
    # return HTMLResponse(content=html_text)


@app.get("/json_demo1")
async def json_demo():
    return {"name": "hui", "age": 18}


@app.get("/json_demo2")
async def json_demo2():
    json_content = {
        "code": 0,
        "message": "ok",
        "data": {"name": "hui", "age": 22}
    }
    return JSONResponse(content=json_content)

async def fake_streamer():
    for i in range(10):
        yield b"streaming fake bytes\n"

@app.get("/stream_demo")
async def stream_demo():
    return StreamingResponse(fake_streamer())


def iter_video(file_path):
    with open(file_path, mode="rb") as file:
        yield from file


@app.get("/stream_video_demo")
async def stream_video_demo():
    video_path = "res/demo.mp4"
    return StreamingResponse(iter_video(video_path), media_type="video/mp4")

@app.get("/file_demo")
async def file_demo():
    video_path = "res/demo.mp4"
    return FileResponse(
        path=video_path, 
        filename="test.mp4", 
        content_disposition_type="inline"
    )

@app.get("/redirect_demo")
async def redirect_demo():
    return RedirectResponse(url="https://juejin.cn/column/7275942983543242767", status_code=301)
